package summer.hot100.v1;

import java.util.*;

public class Solution207 {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        int[] in = new int[numCourses];
        Map<Integer, List<Integer>> map = new HashMap<>();
        for (int[] x : prerequisites) {
            List<Integer> list = map.getOrDefault(x[1], new ArrayList<>());
            list.add(x[0]);
            map.put(x[1], list);
            in[x[0]]++;
        }
        LinkedList<Integer> queue = new LinkedList<>();
        for (int i = 0; i < numCourses; i++) {
            if (in[i] == 0) queue.add(i);
        }
        while (!queue.isEmpty()) {
            int cur = queue.removeFirst();
            List<Integer> list = map.getOrDefault(cur, new ArrayList<>());
            numCourses--;
            for (int x : list) {
                in[x]--;
                if (in[x] == 0) queue.add(x);
            }
        }
        return numCourses == 0;
    }
}
